package com.ls.uav_backend.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 创建一个支持定时任务的线程池
        ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(
                5, // 核心线程数，根据业务量调整
                new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);

                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "scheduled-task-" + threadNumber.getAndIncrement());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：由调用线程执行任务
        );

        // 设置线程池的最大空闲时间
        ((ScheduledThreadPoolExecutor) executor).setKeepAliveTime(30, TimeUnit.SECONDS);

        // 注册线程池
        taskRegistrar.setScheduler(executor);
    }
}
